<?php

class OnlinenewsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		$group_admin = Member::getUserByGroup('admin');
      $group_sp_admin = Member::getUserByGroup('sp_admin');
      return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','checkhot','checkactive','FileManager'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array_merge($group_admin,$group_sp_admin),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new OnlineNews;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['OnlineNews']))
		{
			$model->attributes=$_POST['OnlineNews'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['OnlineNews']))
		{
			$model->attributes=$_POST['OnlineNews'];
			if($model->save())
				$this->redirect(array('admin'));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('OnlineNews');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		
      $model=new OnlineNews('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['OnlineNews']))
			$model->attributes=$_GET['OnlineNews'];
      if (isset($_GET['pageSize'])) {
         Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']);
         unset($_GET['pageSize']);
      }
      if (isset($_POST['ApproveButton'])){ // Nếu click vào nút phê duyệt
        if (isset($_POST['selectedIds']))
        {
            foreach ($_POST['selectedIds'] as $id)
            {
               $detail_online_news = OnlineNews::model()->findByPk($id);
               //CVarDumper::dump($detail_comment);
               if(!is_null($detail_online_news)){
                  $news = new News();
                  $news->title = $detail_online_news->title;
                  $news->cat_id = $detail_online_news->online_news_category_id;
                  $news->image = $detail_online_news->avatar;
                  $news->sapo = $detail_online_news->summary;
                  $news->content = $detail_online_news->content;
                  $news->active = 1;
                  if($news->validate()){
                     if($news->save()){
                        //Cap nhat lai trang thai sync cua tin tuc can duyet
                        $detail_online_news->sync = 1;
                        $detail_online_news->save();
                        //$detail_online_news->delete();
                        News::model()->makeThumbnail($detail_online_news->avatar);
                        $error_code = 200;
                        $message = 'OK';
                     }
                  }else{
                     $error_code = '500';
                     $message = $news->errors;
                  }
               }
            }
        }
      }
      
      if(isset($_POST['DeleteButton'])){ // Nếu click vào nút xóa
         if (isset($_POST['selectedIds']))
         {
            foreach ($_POST['selectedIds'] as $id)
            {
               $detail_online_news = OnlineNews::model()->findByPk($id);
               //CVarDumper::dump($detail_comment);
               if(!is_null($detail_online_news)){
                  $detail_online_news->delete();
               }
            }
         }
      }
      
		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return OnlineNews the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=OnlineNews::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param OnlineNews $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='online-news-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
   
   public function gridContent($data,$row){
      $id = $data->id;
      if($id){
         $detail = OnlineNews::model()->findByPk($id);
         $link = "/news/preview?id=".$detail->id;
         $link_edit = "/index.php/admin/onlinenews/update/id/".$detail->id;
         //$image = (isset($detail->image)) ? Yii::app()->request->baseUrl.'/uploads/pictures/news/'.'s_'.$detail->image : Yii::app()->request->baseUrl.'/images/df_image.png';
         $image = ($detail->avatar != '') ? OnlineNews::model()->getImageFullSize($detail->avatar) : Yii::app()->request->baseUrl.'/images/df_image.png';
         $html = '<div class="left" style="margin-right:10px;width:90px;"><img src="'.$image.'"/></div>';
         $html .= '<strong><a target="_blank" href="'.$link.'">' . $detail->title . '</a></strong>';
         $sapo = ($detail->summary != '') ?  Str::cutString(Str::removeHTML($detail->summary),250) : Str::cutString(Str::removeHTML($detail->content),250);
         $html .= '<p class="sapo" style="margin-right:20px">'.$sapo.'</p>';
         $html .='<div class="row-actions">
                  <span class="approve"><a href="javascript:void(0)" class="text-success" onclick="approve_news('.$data->id.')">Phê duyệt</a></span>
                  <span class="delete "> | <a href="javascript:void(0)" class="text-danger" onclick="delete_news('.$data->id.')">Xóa</a></span>
                  <span class="edit bold"> | <a href="'.$link_edit.'" >Sửa</a></span>
               </div>';
         return $html;   
      }else{
         return '-- Không xác định --';
      }
      
   }
   
   public function gridCate($data,$row){
      $id = $data->online_news_category_id;
      if($id){
         $detail = Category::model()->findByPk($id);
         return $detail->name;   
      }else{
         return '-- Chưa chọn --';
      }
      
   }
   
   /**
    * Duyet va xoa tin tuc crawler
   */
   public function actionHandle(){
      $action = Yii::app()->request->getPost('action');
      $id = Yii::app()->request->getPost('id');
      $error_code = '400';
      $message = 'No action';
      if($action == 'approve'){ // Nếu chọn phê duyệt sẽ chuyển bản ghi sang bảng news
         $detail_online_news = OnlineNews::model()->findByPk($id);
         //CVarDumper::dump($detail_comment);
         if(!is_null($detail_online_news)){
            $news = new News();
            $news->title = $detail_online_news->title;
            $news->cat_id = $detail_online_news->online_news_category_id;
            $news->image = $detail_online_news->avatar;
            $news->sapo = $detail_online_news->summary;
            $news->content = $detail_online_news->content;
            $news->active = 1;
            if($news->validate()){
               if($news->save()){
                  //Cap nhat lai trang thai sync cua tin tuc can duyet
                  $detail_online_news->sync = 1;
                  $detail_online_news->save();
                  //$detail_online_news->delete();
                  
                  //Tao thumbnail cho anh cua tin tuc da duyet
                  
                  News::model()->makeThumbnail($detail_online_news->avatar);
                  $error_code = 200;
                  $message = 'OK';
               }
            }else{
               $error_code = '500';
               $message = $news->errors;
            }
         }
      }
      if($action == 'delete'){// Nếu chọn xóa sẽ xóa bản ghi trong bảng comment
         $detail_online_news = OnlineNews::model()->findByPk($id);
         if(!is_null($detail_online_news)){
            $detail_online_news->delete();
            $error_code = 200;
            $message = 'OK';
         }
      }
      
      echo json_encode(array('error_code' => $error_code,'message' => $message));
   }
   
}
